﻿using Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.VisualBasic;
using MyProject;
using Service;

namespace Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BookController:BaseController
    {
        public IFreeSql _fsql;

        public BookController(IFreeSql fsql)
        {
            _fsql = fsql;
        }

        [HttpPost]
        public ApiModel Add([FromBody] BookDto data)
        {
            var b = new Book() {
                BookName = data.BookName, 
                CreatName = data.CreatName,
                PublishTime = ConvertDatetime(data.PublishTimestr)
            };
            //var sql = _fsql.Insert(b).ToSql();
            //Console.WriteLine(sql);
            var t1 = _fsql.Insert(b).ExecuteAffrows();
            if (t1==0)
            {
                return apiModel(Status.Error, "插入错误");
            }
            else
            {
                return apiModel(Status.Success, "", b);
            }
        }

        //加上Authorize就是验证token，没有Header 里传的话 返回401未验证，因此所有的接口都加
        [HttpPost]
        //[Authorize(Roles ="user")] 
        public ApiModel Get([FromBody] Book data)
        {
            var t1 = _fsql.Select<Book>().Where(a=>a.Id==data.Id).ToOne();
            if (t1 == null)
            {
                return apiModel(Status.Error, "无数据");
            }
            else
            {
                return apiModel(Status.Success, "", t1);
            }
        }
        [HttpPost]
        public ApiModel Delete([FromBody] BookDto data)
        {
            var t1 = _fsql.Delete<Book>(new { id = data.Id }).ExecuteAffrows();
            if (t1 == 0)
            {
                return apiModel(Status.Error, "删除错误");
            }
            else
            {
                return apiModel(Status.Success, "", t1);
            }
        }
        [HttpPost]
        public ApiModel Update([FromBody] Book data)
        {
            var t1 = _fsql.Update<Book>().SetSourceIgnore(data, col => col == null).Where(a => a.Id == data.Id).ExecuteAffrows();
            if (t1 == 0)
            {
                return apiModel(Status.Error, "更新错误");
            }
            else
            {
                return apiModel(Status.Success, "", t1);
            }
        }
        [HttpPost]
        public ApiModel Update2([FromBody] BookDto data)
        {
            var t1 = _fsql.Update<Book>().SetDtoIgnore(data,col=>col==null).Where(a=>a.Id == data.Id).ExecuteAffrows();
            if (t1 == 0)
            {
                return apiModel(Status.Error, "更新错误");
            }
            else
            {
                return apiModel(Status.Success, "", t1);
            }
        }
       
    }
}

